package de.g18.scavengerhunt.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import de.g18.scavengerhunt.types.HttpResourceNotFoundException;
import de.g18.scavengerhunt.types.PostParameter;

/**
 * This util is made for providing methods for easy communication with the web service
 */
public class HttpUtil {
    private List<PostParameter> parameters   = new ArrayList<PostParameter>();

    private String              targetURL    = null;

    private static final int    SC_NOT_FOUND = 404;

    public enum MethodType {
        POST, GET, DELETE;
    }

    public HttpUtil(String targetURL) {
        this.targetURL = targetURL;
    }

    public String executeRequest(String methodType) throws HttpResourceNotFoundException {
        HttpURLConnection conn = null;
        String requestMethod = methodType.toString();

        try {
            URL url = new URL(targetURL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setUseCaches(false);
            conn.setDoInput(true);
            if (requestMethod.equals("POST")) {
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setDoOutput(true);

                String urlParameters = getParameters();
                conn.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
                conn.setRequestProperty("Content-Language", "de-DE");

                // Send request body
                DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(urlParameters);
                wr.flush();
                wr.close();
            } else if (requestMethod.equals("GET") || requestMethod.equals("DELETE")) {
                conn.setDoOutput(false);
            }

            // Get Response
            if (conn.getResponseCode() == SC_NOT_FOUND) {
                throw new HttpResourceNotFoundException();
            } else {
                InputStream is = conn.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                String line;
                StringBuffer response = new StringBuffer();
                while ((line = rd.readLine()) != null) {
                    response.append(line);
                    response.append('\r');
                }
                rd.close();

                return response.toString();
            }
        } catch (Exception e) {
            // TODO Handle timeout
            return null;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    private String getParameters() {
        String retValue = "";
        for (PostParameter currentParam : parameters) {
            if (retValue == null) {
                retValue = currentParam.getNameValuePair();
            } else {
                retValue += "&" + currentParam.getNameValuePair();
            }
        }
        return retValue;
    }

    public void addParameter(String name, String value) {
        parameters.add(new PostParameter(name, value));
    }

}